﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// 
    /// </summary>
    public class Abdunkeln : BaseImageFilter, ITwoSourceFilter
    {
        /// <summary>
        /// 
        /// </summary>
        public Abdunkeln()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_abdunkeln"></param>
        internal Abdunkeln(Abdunkeln _abdunkeln)
        {
        }

        /// <summary>
        /// Executes this filter
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            Process((UnsafeBitmap)_bitmap.Clone(), _bitmap);
            return _bitmap;
        }

        /// <summary>
        /// Process two pics...
        /// </summary>
        /// <param name="_bitmapSource"></param>
        /// <param name="_bitmapDest"></param>
        /// <returns></returns>
        public UnsafeBitmap Process(UnsafeBitmap _bitmapSource, UnsafeBitmap _bitmapDest)
        {
            UnsafeBitmap bitmapSource = _bitmapSource;
            UnsafeBitmap bitmapDest = _bitmapDest;

            Color colorSource = Color.Transparent;
            Color colorDest = Color.Transparent;

            int y = 0;
            int x = 0;

            int nHeight = bitmapSource.Height;
            int nWidth = bitmapSource.Width;

            int nR = 0;
            int nG = 0;
            int nB = 0;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    colorSource = bitmapSource.GetPixel(x, y);
                    colorDest = bitmapDest.GetPixel(x, y);

                    if (colorDest.R <= colorSource.R) nR = colorDest.R; else nR = colorSource.R;
                    if (colorDest.G <= colorSource.G) nG = colorDest.G; else nG = colorSource.G;
                    if (colorDest.B <= colorSource.B) nB = colorDest.B; else nB = colorSource.B;
                    colorDest = Color.FromArgb(nR, nG, nB);
                    bitmapDest.SetPixel(x, y, colorDest);
                }
            }
            bitmapSource.Dispose();
            bitmapDest.Dispose();
            return _bitmapDest;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new Abdunkeln(this);
        }
    }
}
